# LuckPay Web Manage System
#
# Copyright (c) 2016 Lucky Byte, Inc.
#
express = require 'express'
pgsql   = require 'pg'
secure  = require '../lib/secure'
merch_jobs = require '../lib/merch_jobs'
terms_jobs = require '../lib/terms_jobs'
router  = express.Router()
module.exports = router

router.get '/', (req, res, next) ->
    # 检查用户权限
    for perm in req.session.userinfo.permission
        if perm.href is '/merch'
            if not perm.permission.check
                return next new Error('您没有商户复核权限')
        if perm.href is '/terms'
            if not perm.permission.check
                return next new Error('您没有终端复核权限')

    res.render 'wizcheck/index'


router.post '/ajax/wizard_uuids', (req, res, next) ->
    res.type('json')
    for k in ['merch_type']
        return next(new Error("请求缺少参数[#{k}]")) if not req.body[k]

    await pgsql.connect settings.pgsql_url, defer err, client, done
    if err then done(client); return next(err)

    # 删除已经(部分)复核的记录，因为已经部分复核的记录会导致重复复核
    await client.query \
        "delete from pay_wizard where
            merid1  not in (select uuid from pay_merch_ex where action = 1) or
            termid1 not in (select uuid from pay_terms_ex where action = 1) or
            merid2  not in (select uuid from pay_merch_ex where action = 1) or
            termid2 not in (select uuid from pay_terms_ex where action = 1) or
            case
            when merch_type = 1 then
                p1_uuid not in (
                    select uuid from pay_p1 where checked = false and usable = false
                )
            when merch_type = 2 then
                p2_uuid not in (
                    select uuid from pay_p2 where checked = false and usable = false
                )
            end returning uuid", defer err, result
    if err then done(client); return next(err)

    # 只有真正删除了记录的情况下，才需要更新通知
    if result.rows.length > 0
        req.app.set 'notify_modified_time', moment().format('x')

    await client.query \
        "select w.*, m1.merno as merno, m1.name as mername,
            t1.termid as termid
            from pay_wizard as w
            left join pay_merch_ex as m1 on m1.uuid = w.merid1
            left join pay_terms_ex as t1 on t1.uuid = w.termid1
            left join pay_merch_ex as m2 on m2.uuid = w.merid2
            left join pay_terms_ex as t2 on t2.uuid = w.termid2
            where w.merch_type = $1 and w.inputer <> $2 and
                m1.rejected = false and t1.rejected = false and
                m2.rejected = false and t2.rejected = false", [
            req.body.merch_type
            req.session.userinfo.uuid
        ], defer err, result
    if err then done(client); return next(err)
    done()

    if result.rows.length == 0
        return res.json succ: false, errmsg: '未查询到待复核记录'
    res.json succ: true, records: result.rows


# 查询页面下拉表中的数据
router.post '/1', (req, res, next) ->
    for k in ['merch_type', 'wizard_uuid']
        return next(new Error("请求缺少参数[#{k}]")) if not req.body[k]

    await pgsql.connect settings.pgsql_url, defer err, client, done
    if err then done(client); return next(err)

    # 手续费列表
    await client.query \
        "select * from pay_fee", defer err, result
    if err then done(client); return next(err)
    res.locals.fees = result.rows
    done()
    next()


router.post '/1', (req, res, next) ->
    await pgsql.connect settings.pgsql_url, defer err, client, done
    if err then done(client); return next(err)

    await client.query \
        "select w.*,
            m1.merno as t20_merno, m1.name as name, m1.contact as contact,
            m1.address as address, m1.mobile as mobile, m1.email as email,
            m1.unit_name as unit_name, m1.unit_english as unit_english,
            m1.unit_name_abbr as unit_name_abbr,
            m1.unit_english_abbr as unit_english_abbr,
            m1.unit_code as unit_code, m1.unit_tax_code as unit_tax_code,
            m1.unit_legal_name as unit_legal_name,
            m1.unit_cred_type as unit_cred_type,
            m1.unit_cred_no as unit_cred_no, m1.unit_assets as unit_assets,
            m1.unit_license as unit_license,
            m1.unit_license_exp as unit_license_exp,
            m1.unit_issuer as unit_issuer, m1.unit_type as unit_type,
            m1.unit_address as unit_address, m1.unit_scope as unit_scope,
            json_extract_path_text(
                m1.trctl, 't20', 'time_begin') as time_begin,
            json_extract_path_text(
                m1.trctl, 't20', 'time_end') as time_end,
            json_extract_path_text(
                m1.trctl, 't20', 'min_amt_per') as min_amt_per,
            json_extract_path_text(
                m1.trctl, 't20', 'min_amt_per2') as min_amt_per2,
            json_extract_path_text(
                m1.trctl, 't20', 'max_amt_per') as max_amt_per,
            json_extract_path_text(
                m1.trctl, 't20', 'max_amt_per2') as max_amt_per2,
            json_extract_path_text(
                m1.trctl, 't20', 'max_amt_minute') as max_amt_minute,
            json_extract_path_text(
                m1.trctl, 't20', 'max_cnt_minute') as max_cnt_minute,
            json_extract_path_text(
                m1.trctl, 't20', 'max_amt_day') as max_amt_day,
            json_extract_path_text(
                m1.trctl, 't20', 'max_cnt_day') as max_cnt_day,
            m1.t20_fee as t20_fee,
            t1.termid as t20_termid,
            m2.merno as tz0_merno, t2.termid as tz0_termid,
            t2.macalgo as tz0_macalgo, t2.tmk as tz0_tmk,
            json_extract_path_text(
                p1.check_data, 'data', 'acct_cred_type') as acct_cred_type,
            json_extract_path_text(
                p1.check_data, 'data', 'acct_mobile') as acct_mobile,
            json_extract_path_text(
                p1.check_data, 'data', 'acct_bank_code') as acct_bank_code,
            json_extract_path_text(
                p1.check_data, 'data', 'acct_bank_name') as acct_bank_name,
            json_extract_path_text(
                p1.check_data, 'data', 'pay_chnl') as pay_chnl,
            json_extract_path_text(
                p1.check_data, 'data', 'pay_merid') as pay_merid
        from pay_wizard as w
        left join pay_merch_ex as m1 on m1.uuid = w.merid1
        left join pay_terms_ex as t1 on t1.uuid = w.termid1
        left join pay_merch_ex as m2 on m2.uuid = w.merid2
        left join pay_terms_ex as t2 on t2.uuid = w.termid2
        left join pay_p1 as p1 on p1.uuid = w.p1_uuid
        where w.merch_type = 1 and w.inputer <> $1 and w.uuid = $2", [
            req.session.userinfo.uuid
            req.body.wizard_uuid
        ], defer err, result
    if err then done(client); return next(err)

    if result.rows.length == 0
        return next new Error('未查询到待复核记录，请检查.')

    res.locals.record = result.rows[0]

    # 终端主密钥解密
    res.locals.record.tz0_tmk = secure.decryptEde res.locals.record.tz0_tmk

    # 查询代付商户列表
    await client.query "select * from pay_merch where
        chnl = $1 and inside = false and
        disabled = false and shaded = false", [
            res.locals.record.pay_chnl
        ], defer err, result
    if err then done(client); return next(err)
    res.locals.pay_merids = result.rows
    done()
    res.render "wizcheck/check_1"


# 检查复核的账号与录入的账号一致
router.post '/check/1/pass', (req, res, next) ->
    for k in ['uuid', 'acct_no', 'effect_time']
        return next(new Error("请求缺少参数[#{k}]")) if not req.body[k]

    await pgsql.connect settings.pgsql_url, defer err, client, done
    if err then done(client); return next(err)

    await client.query \
        "select w.*,
            json_extract_path_text(p1.check_data, 'data', 'acct_no') as acct_no,
            json_extract_path_text(p1.check_data, 'data', 'acct_name') as acct_name,
            json_extract_path_text(p1.check_data, 'data', 'acct_cred_no') as acct_cred_no
        from pay_wizard as w
        left join pay_p1 as p1 on p1.uuid = w.p1_uuid
        where w.merch_type = 1 and w.inputer <> $1 and w.uuid = $2", [
            req.session.userinfo.uuid
            req.body.uuid
        ], defer err, result
    if err then done(client); return next(err)
    done()

    if result.rows.length == 0
        return next new Error('未找到待复核记录，请检查')

    req.wizard_record = result.rows[0]

    # 验证用户复核时再次输入的信息与录入时的一致
    if req.body.acct_no isnt req.wizard_record.acct_no
        return next new Error('您输入的收款账号与录入时用户输入的不一致')

    req.body.acct_name = req.body.acct_name or ''
    req.wizard_record.acct_name = req.wizard_record.acct_name or ''
    if req.body.acct_name isnt req.wizard_record.acct_name
        return next new Error('您输入的收款账户姓名与录入时用户输入的不一致')

    req.body.acct_cred_no = req.body.acct_cred_no or ''
    req.wizard_record.acct_cred_no = req.wizard_record.acct_cred_no or ''
    if req.body.acct_cred_no isnt req.wizard_record.acct_cred_no
        return next new Error('您输入的收款账户证件号码与录入时用户输入的不一致')

    next()


# 在一个事务中处理
router.post '/check/1/pass', (req, res, next) ->
    await pgsql.connect settings.pgsql_url, defer err, client, done
    if err then done(client); return next(err)

    await client.query "begin", defer err, result
    if err then done(client); return next(err)

    req.client = client
    req.done = done
    next()


# 复核消费商户/代付商户
router.post '/check/1/pass', (req, res, next) ->
    await req.client.query \
        "update pay_merch_ex set checked = true, checker = $1,
            check_time = CURRENT_TIMESTAMP, effect_time = $2,
            rejected = false, reject_reason = ''
        where uuid in ($3, $4)", [
            req.session.userinfo.uuid
            req.body.effect_time
            req.wizard_record.merid1
            req.wizard_record.merid2
        ], defer err, result
    if err then req.done(req.client); return next(err)
    next()


# 复核消费终端/代付终端
router.post '/check/1/pass', (req, res, next) ->
    await req.client.query \
        "update pay_terms_ex set checked = true, checker = $1,
            check_time = CURRENT_TIMESTAMP, effect_time = $2,
            rejected = false, reject_reason = ''
        where uuid in ($3, $4)", [
            req.session.userinfo.uuid
            req.body.effect_time
            req.wizard_record.termid1
            req.wizard_record.termid2
        ], defer err, result
    if err then req.done(req.client); return next(err)
    next()


# 复核消费代付配置
router.post '/check/1/pass', (req, res, next) ->
    await req.client.query \
        "select check_data from pay_p1 where
            checked = false and inputer <> $1 and uuid = $2", [
            req.session.userinfo.uuid
            req.wizard_record.p1_uuid
        ], defer err, result
    if err then req.done(client); return next(err)
    if result.rows.length == 0
        return next new Error('未查询到待复核记录，请检查.')

    check_data = result.rows[0].check_data

    await req.client.query \
        "update pay_p1 set usable = true, checked = true,
            checker = $1, check_time = CURRENT_TIMESTAMP,
            t20_merid = $2,     t20_termid = $3,
            tz0_merid = $4,     tz0_termid = $5,
            pay_chnl = $6,      pay_merid = $7,
            acct_no = $8,       acct_name = $9,
            acct_cred_no = $10, acct_cred_type = $11,
            acct_mobile = $12,  acct_bank_code = $13,
            acct_bank_name = $14,   notes = $15,
            check_data = null
        where
            checked = false and inputer <> $16 and uuid = $17", [
            req.session.userinfo.uuid
            check_data.data.t20_merid
            check_data.data.t20_termid
            check_data.data.tz0_merid
            check_data.data.tz0_termid
            check_data.data.pay_chnl
            check_data.data.pay_merid
            check_data.data.acct_no
            check_data.data.acct_name
            check_data.data.acct_cred_no
            parseInt(check_data.data.acct_cred_type)
            check_data.data.acct_mobile
            check_data.data.acct_bank_code
            check_data.data.acct_bank_name
            check_data.data.notes
            req.session.userinfo.uuid
            req.wizard_record.p1_uuid
        ], defer err, result
    if err then req.done(req.client); return next(err)
    next()


# 删除入户向导记录
router.post '/check/1/pass', (req, res, next) ->
    await req.client.query \
        "delete from pay_wizard where uuid = $1", [
            req.wizard_record.uuid
        ], defer err, result
    if err then req.done(req.client); return next(err)
    next()


router.post '/check/1/pass', (req, res, next) ->
    await req.client.query "commit", defer err, result
    req.done()

    # 增加调度器，在将来某个时间让商户生效
    merch_jobs.sched_effect req.wizard_record.merid1, req.body.effect_time
    merch_jobs.sched_effect req.wizard_record.merid2, req.body.effect_time
    terms_jobs.sched_effect req.wizard_record.termid1, req.body.effect_time
    terms_jobs.sched_effect req.wizard_record.termid2, req.body.effect_time

    req.app.set 'notify_modified_time', moment().format('x')
    res.redirect '/wizcheck'


router.post '/check/1/reject', (req, res, next) ->
    for k in ['uuid', 'acct_no', 'reject_reason']
        return next(new Error("请求缺少参数[#{k}]")) if not req.body[k]

    await pgsql.connect settings.pgsql_url, defer err, client, done
    if err then done(client); return next(err)

    await client.query \
        "select w.* from pay_wizard as w
            where w.merch_type = 1 and w.inputer <> $1 and w.uuid = $2", [
            req.session.userinfo.uuid
            req.body.uuid
        ], defer err, result
    if err then done(client); return next(err)
    done()

    if result.rows.length == 0
        return next new Error('未查询到待复核记录，请检查')

    req.wizard_record = result.rows[0]
    next()


# 在一个事务中处理
router.post '/check/1/reject', (req, res, next) ->
    await pgsql.connect settings.pgsql_url, defer err, client, done
    if err then done(client); return next(err)

    await client.query "begin", defer err, result
    if err then done(client); return next(err)

    req.client = client
    req.done = done
    next()


# 更新商户状态为拒绝
router.post '/check/1/reject', (req, res, next) ->
    await req.client.query \
        "update pay_merch_ex set checked = false, checker = $1,
            check_time = CURRENT_TIMESTAMP,
            rejected = true, reject_reason = $2
        where uuid in ($3, $4)", [
            req.session.userinfo.uuid
            req.body.reject_reason
            req.wizard_record.merid1
            req.wizard_record.merid2
        ], defer err, result
    if err then req.done(req.client); return next(err)
    next()

# 更新终端状态为拒绝
router.post '/check/1/reject', (req, res, next) ->
    await req.client.query \
        "update pay_terms_ex set checked = false, checker = $1,
            check_time = CURRENT_TIMESTAMP,
            rejected = true, reject_reason = $2
        where uuid in ($3, $4)", [
            req.session.userinfo.uuid
            req.body.reject_reason
            req.wizard_record.termid1
            req.wizard_record.termid2
        ], defer err, result
    if err then req.done(req.client); return next(err)
    next()


router.post '/check/1/reject', (req, res, next) ->
    await req.client.query "commit", defer err, result
    req.done()
    req.app.set 'notify_modified_time', moment().format('x')
    res.redirect '/wizcheck'


# 查询页面下拉表中的数据
router.post '/2', (req, res, next) ->
    for k in ['merch_type', 'wizard_uuid']
        return next(new Error("请求缺少参数[#{k}]")) if not req.body[k]

    await pgsql.connect settings.pgsql_url, defer err, client, done
    if err then done(client); return next(err)

    # 手续费列表
    await client.query \
        "select * from pay_fee", defer err, result
    if err then done(client); return next(err)
    res.locals.fees = result.rows

    # 资金池列表
    await client.query \
        "select * from pay_p2_fund", defer err, result
    if err then done(client); return next(err)
    res.locals.p2_funds = result.rows
    done()
    next()


router.post '/2', (req, res, next) ->
    await pgsql.connect settings.pgsql_url, defer err, client, done
    if err then done(client); return next(err)

    await client.query \
        "select w.*,
            m1.merno as t60_merno, m1.name as name, m1.contact as contact,
            m1.address as address, m1.mobile as mobile, m1.email as email,
            m1.unit_name as unit_name, m1.unit_english as unit_english,
            m1.unit_name_abbr as unit_name_abbr,
            m1.unit_english_abbr as unit_english_abbr,
            m1.unit_code as unit_code, m1.unit_tax_code as unit_tax_code,
            m1.unit_legal_name as unit_legal_name,
            m1.unit_cred_type as unit_cred_type,
            m1.unit_cred_no as unit_cred_no, m1.unit_assets as unit_assets,
            m1.unit_license as unit_license,
            m1.unit_license_exp as unit_license_exp,
            m1.unit_issuer as unit_issuer, m1.unit_type as unit_type,
            m1.unit_address as unit_address, m1.unit_scope as unit_scope,
            json_extract_path_text(
                m1.trctl, 't60', 'time_begin') as time_begin,
            json_extract_path_text(
                m1.trctl, 't60', 'time_end') as time_end,
            json_extract_path_text(
                m1.trctl, 't60', 'min_amt_per') as min_amt_per,
            json_extract_path_text(
                m1.trctl, 't60', 'min_amt_per2') as min_amt_per2,
            json_extract_path_text(
                m1.trctl, 't60', 'max_amt_per') as max_amt_per,
            json_extract_path_text(
                m1.trctl, 't60', 'max_amt_per2') as max_amt_per2,
            json_extract_path_text(
                m1.trctl, 't60', 'max_amt_minute') as max_amt_minute,
            json_extract_path_text(
                m1.trctl, 't60', 'max_cnt_minute') as max_cnt_minute,
            json_extract_path_text(
                m1.trctl, 't60', 'max_amt_day') as max_amt_day,
            json_extract_path_text(
                m1.trctl, 't60', 'max_cnt_day') as max_cnt_day,
            t1.termid as t60_termid,
            m2.merno as tz1_merno, t2.termid as tz1_termid,
            t2.macalgo as tz1_macalgo, t2.tmk as tz1_tmk,
            json_extract_path_text(
                p2.check_data, 'data', 't60_fee') as t60_fee,
            json_extract_path_text(
                p2.check_data, 'data', 'p2_fund') as p2_fund,
            json_extract_path_text(
                p2.check_data, 'data', 'fee_take_type') as fee_take_type,
            json_extract_path_text(
                p2.check_data, 'data', 'fund_lack_proc') as fund_lack_proc,
            json_extract_path_text(
                p2.check_data, 'data', 'acct_cred_type') as acct_cred_type,
            json_extract_path_text(
                p2.check_data, 'data', 'acct_mobile') as acct_mobile,
            json_extract_path_text(
                p2.check_data, 'data', 'acct_bank_code') as acct_bank_code,
            json_extract_path_text(
                p2.check_data, 'data', 'acct_bank_name') as acct_bank_name,
            json_extract_path_text(
                p2.check_data, 'data', 'pay_chnl') as pay_chnl,
            json_extract_path_text(
                p2.check_data, 'data', 'pay_merid') as pay_merid
        from pay_wizard as w
        left join pay_merch_ex as m1 on m1.uuid = w.merid1
        left join pay_terms_ex as t1 on t1.uuid = w.termid1
        left join pay_merch_ex as m2 on m2.uuid = w.merid2
        left join pay_terms_ex as t2 on t2.uuid = w.termid2
        left join pay_p2 as p2 on p2.uuid = w.p2_uuid
        where w.merch_type = 2 and w.inputer <> $1 and w.uuid = $2", [
            req.session.userinfo.uuid
            req.body.wizard_uuid
        ], defer err, result
    if err then done(client); return next(err)

    if result.rows.length == 0
        return next new Error('未查询到待复核记录，请检查.')

    res.locals.record = result.rows[0]

    # 终端主密钥解密
    res.locals.record.tz1_tmk = secure.decryptEde res.locals.record.tz1_tmk

    # 查询代付商户列表
    await client.query "select * from pay_merch where
        chnl = $1 and inside = false and
        disabled = false and shaded = false", [
            res.locals.record.pay_chnl
        ], defer err, result
    if err then done(client); return next(err)
    res.locals.pay_merids = result.rows
    done()
    res.render "wizcheck/check_2"


# 检查复核的账号与录入的账号一致
router.post '/check/2/pass', (req, res, next) ->
    for k in ['uuid', 'acct_no', 'effect_time']
        return next(new Error("请求缺少参数[#{k}]")) if not req.body[k]

    await pgsql.connect settings.pgsql_url, defer err, client, done
    if err then done(client); return next(err)

    await client.query \
        "select w.*,
            json_extract_path_text(p2.check_data, 'data', 'acct_no') as acct_no,
            json_extract_path_text(p2.check_data, 'data', 'acct_name') as acct_name,
            json_extract_path_text(p2.check_data, 'data', 'acct_cred_no') as acct_cred_no
        from pay_wizard as w
        left join pay_p2 as p2 on p2.uuid = w.p2_uuid
        where w.merch_type = 2 and w.inputer <> $1 and w.uuid = $2", [
            req.session.userinfo.uuid
            req.body.uuid
        ], defer err, result
    if err then done(client); return next(err)
    done()

    if result.rows.length == 0
        return next new Error('未找到待复核记录，请检查')

    req.wizard_record = result.rows[0]

    if req.body.acct_no isnt req.wizard_record.acct_no
        return next new Error('您输入的收款账号与录入时用户输入的账号不一致')

    req.body.acct_name = req.body.acct_name or ''
    req.wizard_record.acct_name = req.wizard_record.acct_name or ''
    if req.body.acct_name isnt req.wizard_record.acct_name
        return next new Error('您输入的收款账户姓名与录入时用户输入的不一致')

    req.body.acct_cred_no = req.body.acct_cred_no or ''
    req.wizard_record.acct_cred_no = req.wizard_record.acct_cred_no or ''
    if req.body.acct_cred_no isnt req.wizard_record.acct_cred_no
        return next new Error('您输入的收款账户证件号码与录入时用户输入的不一致')

    next()


# 在一个事务中处理
router.post '/check/2/pass', (req, res, next) ->
    await pgsql.connect settings.pgsql_url, defer err, client, done
    if err then done(client); return next(err)

    await client.query "begin", defer err, result
    if err then done(client); return next(err)

    req.client = client
    req.done = done
    next()


# 复核取款商户/代付商户
router.post '/check/2/pass', (req, res, next) ->
    await req.client.query \
        "update pay_merch_ex set checked = true, checker = $1,
            check_time = CURRENT_TIMESTAMP, effect_time = $2,
            rejected = false, reject_reason = ''
        where uuid in ($3, $4)", [
            req.session.userinfo.uuid
            req.body.effect_time
            req.wizard_record.merid1
            req.wizard_record.merid2
        ], defer err, result
    if err then req.done(req.client); return next(err)
    next()


# 复核取款终端/代付终端
router.post '/check/2/pass', (req, res, next) ->
    await req.client.query \
        "update pay_terms_ex set checked = true, checker = $1,
            check_time = CURRENT_TIMESTAMP, effect_time = $2,
            rejected = false, reject_reason = ''
        where uuid in ($3, $4)", [
            req.session.userinfo.uuid
            req.body.effect_time
            req.wizard_record.termid1
            req.wizard_record.termid2
        ], defer err, result
    if err then req.done(req.client); return next(err)
    next()


# 复核助农取款代付配置
router.post '/check/2/pass', (req, res, next) ->
    await req.client.query \
        "select check_data from pay_p2 where
            checked = false and inputer <> $1 and uuid = $2", [
            req.session.userinfo.uuid
            req.wizard_record.p2_uuid
        ], defer err, result
    if err then req.done(req.client); return next(err)
    if result.rows.length == 0
        return next new Error('未查询到待复核记录，请检查.')

    check_data = result.rows[0].check_data

    await req.client.query \
        "update pay_p2 set usable = true,  checked = true,
            checker = $1,       check_time = CURRENT_TIMESTAMP,
            t60_merid = $2,     t60_termid = $3,
            tz1_merid = $4,     tz1_termid = $5,
            t60_fee = $6,       p2_fund = $7,
            fee_take_type = $8, fund_lack_proc = $9,
            pay_chnl = $10,     pay_merid = $11,
            acct_no = $12,      acct_name = $13,
            acct_cred_no = $14, acct_cred_type = $15,
            acct_mobile = $16,  acct_bank_code = $17,
            acct_bank_name = $18,   notes = $19,
            check_data = null
        where
            checked = false and inputer <> $20 and uuid = $21", [
            req.session.userinfo.uuid
            check_data.data.t60_merid
            check_data.data.t60_termid
            check_data.data.tz1_merid
            check_data.data.tz1_termid
            check_data.data.t60_fee
            check_data.data.p2_fund
            check_data.data.fee_take_type
            check_data.data.fund_lack_proc
            check_data.data.pay_chnl
            check_data.data.pay_merid
            check_data.data.acct_no
            check_data.data.acct_name
            check_data.data.acct_cred_no
            parseInt(check_data.data.acct_cred_type)
            check_data.data.acct_mobile
            check_data.data.acct_bank_code
            check_data.data.acct_bank_name
            check_data.data.notes
            req.session.userinfo.uuid
            req.wizard_record.p2_uuid
        ], defer err, result
    if err then req.done(req.client); return next(err)
    next()


# 删除入户向导记录
router.post '/check/2/pass', (req, res, next) ->
    await req.client.query \
        "delete from pay_wizard where uuid = $1", [
            req.wizard_record.uuid
        ], defer err, result
    if err then req.done(req.client); return next(err)
    next()


router.post '/check/2/pass', (req, res, next) ->
    await req.client.query "commit", defer err, result
    req.done()

    # 增加调度器，在将来某个时间让商户生效
    merch_jobs.sched_effect req.wizard_record.merid1, req.body.effect_time
    merch_jobs.sched_effect req.wizard_record.merid2, req.body.effect_time
    terms_jobs.sched_effect req.wizard_record.termid1, req.body.effect_time
    terms_jobs.sched_effect req.wizard_record.termid2, req.body.effect_time

    req.app.set 'notify_modified_time', moment().format('x')
    res.redirect '/wizcheck'


router.post '/check/2/reject', (req, res, next) ->
    for k in ['uuid', 'acct_no', 'reject_reason']
        return next(new Error("请求缺少参数[#{k}]")) if not req.body[k]

    await pgsql.connect settings.pgsql_url, defer err, client, done
    if err then done(client); return next(err)

    await client.query \
        "select w.* from pay_wizard as w
            where w.merch_type = 2 and w.inputer <> $1 and w.uuid = $2", [
            req.session.userinfo.uuid
            req.body.uuid
        ], defer err, result
    if err then done(client); return next(err)
    done()

    if result.rows.length == 0
        return next new Error('未查询到待复核记录，请检查')

    req.wizard_record = result.rows[0]
    next()


# 在一个事务中处理
router.post '/check/2/reject', (req, res, next) ->
    await pgsql.connect settings.pgsql_url, defer err, client, done
    if err then done(client); return next(err)

    await client.query "begin", defer err, result
    if err then done(client); return next(err)

    req.client = client
    req.done = done
    next()


# 更新商户状态为拒绝
router.post '/check/2/reject', (req, res, next) ->
    await req.client.query \
        "update pay_merch_ex set checked = false, checker = $1,
            check_time = CURRENT_TIMESTAMP,
            rejected = true, reject_reason = $2
        where uuid in ($3, $4)", [
            req.session.userinfo.uuid
            req.body.reject_reason
            req.wizard_record.merid1
            req.wizard_record.merid2
        ], defer err, result
    if err then req.done(req.client); return next(err)
    next()

# 更新终端状态为拒绝
router.post '/check/2/reject', (req, res, next) ->
    await req.client.query \
        "update pay_terms_ex set checked = false, checker = $1,
            check_time = CURRENT_TIMESTAMP,
            rejected = true, reject_reason = $2
        where uuid in ($3, $4)", [
            req.session.userinfo.uuid
            req.body.reject_reason
            req.wizard_record.termid1
            req.wizard_record.termid2
        ], defer err, result
    if err then req.done(req.client); return next(err)
    next()


router.post '/check/2/reject', (req, res, next) ->
    await req.client.query "commit", defer err, result
    req.done()
    req.app.set 'notify_modified_time', moment().format('x')
    res.redirect '/wizcheck'
